package com.hankol.winecellar.utils

import android.app.Activity
import android.app.AlertDialog
import android.app.AppOpsManager
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.core.app.AppOpsManagerCompat
import com.baselibrary.MessageBus
import com.baselibrary.extension.addTextChangedListenerClosure
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.utils.CommonUtil
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.utils.PopUtils
import com.google.android.flexbox.FlexboxLayout
import com.hankol.winecellar.R
import com.hankol.winecellar.bean.AllComponyBean
import com.hankol.winecellar.bean.WineryDataInfoBean
import com.hankol.winecellar.view.MyCircleProgress
import com.baselibrary.view.WheelView
import com.xinlan.imageeditlibrary.editimage.utils.DensityUtil


object PopUtils {

    /**酒窖服务 弹窗
     * @author: merbng
     * @time: 2021/11/30 14:18
     * @description:
     */
    fun showWinecellarServiceDialog(act: Activity, mDataBean: WineryDataInfoBean) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        window.setContentView(R.layout.pop_winecellar_service)
        window.setGravity(Gravity.BOTTOM)
        mDataBean?.let {
            window.findViewById<TextView>(R.id.tv_start_end_time).text = "${it.startTime}-${it.endTime}"
            val flSpecial = window.findViewById<FlexboxLayout>(R.id.fl_label_special)
            flSpecial.removeAllViews()
            it.wineryLabelConfigFeature?.forEach {
                FlexBoxUtils.addChildToFlexboxLayout4Pop(flSpecial, it)
            }
            val flBase = window.findViewById<FlexboxLayout>(R.id.fl_label_base)
            flBase.removeAllViews()
            it.wineryLabelConfigFacility?.forEach {
                FlexBoxUtils.addChildToFlexboxLayoutNoBg(flBase, it)
            }
        }

        window.findViewById<TextView>(R.id.tv_title)
        window.findViewById<ImageView>(R.id.img_close).setOnClickListener {
            dialog.dismiss()
        }
//        window.findViewById<View>(R.id.v_temp).visibility =
//            if (AppUtils.isHuaWeiPhone()) View.VISIBLE else View.GONE
    }

    interface ISendGoodsCallback {
        fun onClickSendGoods(type: String, code: String)
    }

    /**发货，填写发货信息 弹窗
     * @author: merbng
     * @time: 2022/8/6 15:08
     * @description: isChange:true  修改发货信息   false ：填写发货信息
     */
    @JvmStatic
    fun showSendGoodsDialog(act: Activity, companyList: MutableList<AllComponyBean>, type: String, code: String, isChange: Boolean = false, callback: ISendGoodsCallback) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.dialog_send_goods, null)

        val spinner = view.findViewById<Spinner>(R.id.spinner)
        val etCode = view.findViewById<EditText>(R.id.et_code)
        val tvOk = view.findViewById<TextView>(R.id.tv_ok)
        view.findViewById<TextView>(R.id.tv_title).setText(if (isChange) "修改发货信息" else "填写发货信息")
        tvOk.setText(if (isChange) "确认" else "确认发货")
        var typeName = ""
        var tempIndex = 0
        companyList.forEachIndexed { index, allComponyBean ->
            if (allComponyBean.code == type) {
                typeName = allComponyBean.name
                tempIndex = index
            }
        }
        var selectStyle = if (type.isNullOrEmpty()) "请选择" else typeName
        var kuaidiType = type
        etCode.setText("${code}")
        etCode.addTextChangedListenerClosure(afterTextChanged = {
            if (it.toString().length >= 10 && selectStyle != "请选择") {
                tvOk.setBackgroundResource(R.drawable.bg_solid_f54d53_r20)
            } else {
                tvOk.setBackgroundResource(R.drawable.bg_solid_f54d53_r20_a50)
            }
        })
        companyList.add(0, AllComponyBean("", "请选择"))
        val adapter = ArrayAdapter(act, R.layout.item_spinner_express, R.id.tv_title, companyList.map { it.name })
        //设置下拉列表的风格
        adapter.setDropDownViewResource(R.layout.item_spinner_express_pop)
        //将adapter 添加到spinner中
        spinner.setAdapter(adapter);
        spinner.setSelection(if (tempIndex == 0) tempIndex else tempIndex.plus(1))//因为有个第一个请选择的占位
        //添加事件Spinner事件监听
        spinner.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                selectStyle = companyList[position].name
                kuaidiType = companyList[position].code
                if (position == 0) {
                    //没选
                    tvOk.setBackgroundResource(R.drawable.bg_solid_f54d53_r20_a50)
                } else {
                    if (etCode.text.toString().checkNotNull() && kuaidiType.checkNotNull()) {
                        tvOk.setBackgroundResource(R.drawable.bg_solid_f54d53_r20)
                    } else {
                        tvOk.setBackgroundResource(R.drawable.bg_solid_f54d53_r20_a50)
                    }
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        })
        tvOk.setOnClickListener {
            if (selectStyle != "请选择" && etCode.text.toString().checkNotNull() && etCode.text.toString().length >= 10) {
                callback.onClickSendGoods(kuaidiType, etCode.text.toString())
                dialog.dismiss()
            }
        }
        window.setContentView(view)
        window.setGravity(Gravity.CENTER)
    }

    interface IGoodsSortCallback {
        fun onClickOk(num: String)
    }

    /**商品排序弹窗
     * @author: merbng
     * @time: 2022/9/6 15:20
     * @description:
     */
    @JvmStatic
    fun showGoodsSortDialog(act: Activity, num: Long = 0, callback: IGoodsSortCallback) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.dialog_change_goods_sort, null)
        val etCode = view.findViewById<EditText>(R.id.et_code)
        val tvOk = view.findViewById<TextView>(R.id.tv_ok)
        view.findViewById<ImageView>(R.id.img_close).setOnClickListener { dialog.dismiss() }
        etCode.setText("${num}")
        etCode.setSelection(etCode.text.toString().length)
        etCode.addTextChangedListenerClosure(afterTextChanged = {
            if (it.toString().length != 0) {
                tvOk.setBackgroundResource(R.drawable.bg_solid_f54d53_r20)
            } else {
                tvOk.setBackgroundResource(R.drawable.bg_solid_f54d53_r20_a50)
            }
        })
        tvOk.setOnClickListener {
            if (etCode.text.toString().checkNotNull()) {
                callback.onClickOk(etCode.text.toString())
                dialog.dismiss()
            }
        }
        window.setContentView(view)
        window.setGravity(Gravity.CENTER)
    }

    /**位置权限 弹窗
     * @author: merbng
     * @time: 2022/11/9 11:04
     * @description:
     */
    fun showLocationPermissionDialog(act: Activity) {
        //是否开启定位服务
        val locationEnabled = CommonUtil.isLocationEnabled(act)
        if (locationEnabled) {
            //检测用户是否将当前应用的定位权限拒绝
            val checkResult = CommonUtil.checkOp(act, 2, AppOpsManager.OPSTR_FINE_LOCATION);//其中2代表AppOpsManager.OP_GPS，如果要判断悬浮框权限，第二个参数需换成24即AppOpsManager。OP_SYSTEM_ALERT_WINDOW及，第三个参数需要换成AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW
            val checkResult2 = CommonUtil.checkOp(act, 1, AppOpsManager.OPSTR_FINE_LOCATION);
            if (AppOpsManagerCompat.MODE_IGNORED == checkResult || AppOpsManagerCompat.MODE_IGNORED == checkResult2) {
                //未开启定位权限或者被拒绝的操作
                //弹窗
                onlyShowLocationDialog(act)
            } else {
                //已开权限
                //权限通过
                EventBusUtils.sendNotify(MessageBus.msgId_location_permission_pass)
            }
        } else {
            //弹窗
            onlyShowLocationDialog(act)
        }
    }
    private fun onlyShowLocationDialog(act: Activity) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = DensityUtil.dip2px(act,265f)
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.dialog_location_permission, null)
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            dialog.dismiss()
        }
        view.findViewById<TextView>(R.id.tv_go_set).setOnClickListener {
            dialog.dismiss()
            //是否开启定位服务
            val locationEnabled = CommonUtil.isLocationEnabled(act)
            if (locationEnabled) {
                //开了服务，未开启权限
                PermissionsUtils.getInstance().chekPermissions(act, PermissionCollection.LOCATION.getPermissionList(), object : PermissionsCall() {
                    override fun permissionsPass() {
                        //权限通过
                        EventBusUtils.sendNotify(MessageBus.msgId_location_permission_pass)
                    }

                    override fun permissionsRefuse(strPer: ArrayList<String>) {
                        //权限拒绝
                    }
                })
            } else {
                //未开启服务
                CommonUtil.openGpsSettings()
            }
        }
        window.setContentView(view)
        window.setGravity(Gravity.CENTER)
    }

    interface ICallback4Progress {
        fun progressCallback(progressView: MyCircleProgress, tvProgress: TextView)
    }

    //发布 线上酒币编辑、发布下酒菜（编辑）、发布评论（编辑）、发布酒窖动态在发布页面点击“发布”时增加loading
    fun uploadLoadingDialog(act: Activity, callback: ICallback4Progress): AlertDialog {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        window.setContentView(R.layout.dialog_uploading)
        window.setGravity(Gravity.CENTER)
        val progressView = window.findViewById<MyCircleProgress>(R.id.pro)
        val tvTip = window.findViewById<TextView>(R.id.tv_bottom_tip)
        callback.progressCallback(window.findViewById<MyCircleProgress>(R.id.pro), tvTip)
        if (progressView.current == 100) {
            tvTip.text = "请稍后"
            progressView.postDelayed(Runnable { dialog.dismiss() }, 1000)
        }
        return dialog
    }

    interface IitemCallBackStr {
        fun onOkClick(startTimeStr: String, endTimeStr: String)
    }
    //00:00--23:59 时间段选择弹窗
    fun showHourMinuteTimeSectionSelectDialog(act: Activity, callback: PopUtils.IitemCallBackStr) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        window.setContentView(R.layout.pop_hour_minute_time_section_select)
        window.setGravity(Gravity.BOTTOM)
        val wheelHour1 = window.findViewById<WheelView>(R.id.wv_hour_1)
        val wheelMinute1 = window.findViewById<WheelView>(R.id.wv_minute_1)
        val wheelHour2 = window.findViewById<WheelView>(R.id.wv_hour_2)
        val wheelMinute2 = window.findViewById<WheelView>(R.id.wv_minute_2)

        val hourList = mutableListOf<String>()
        val minuteList = mutableListOf<String>()
        var houtStr1 = ""
        var minuteStr1 = ""
        var houtStr2 = ""
        var minuteStr2 = ""

        for (i in 0..23) {
            hourList.add(if (i < 10) "0${i}" else "${i}")
        }
        for (i in 0..59) {
            minuteList.add(if (i < 10) "0${i}" else "${i}")
        }
        wheelHour1.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelHour1.setItems(hourList);// 设置数据源
        wheelHour1.setSeletion(0);// 默认选中第三项
        wheelHour1.setOnWheelViewListener(object : WheelView.OnWheelViewListener() {
            override fun onSelected(selectedIndex: Int, item: String?) {
                super.onSelected(selectedIndex, item)
                houtStr1 = item.checkValue()
            }
        })
        wheelMinute1.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelMinute1.setItems(minuteList);// 设置数据源
        wheelMinute1.setSeletion(0);// 默认选中第三项
        wheelMinute1.setOnWheelViewListener(object : WheelView.OnWheelViewListener() {
            override fun onSelected(selectedIndex: Int, item: String?) {
                super.onSelected(selectedIndex, item)
                minuteStr1 = item.checkValue()
            }
        })
        wheelHour2.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelHour2.setItems(hourList);// 设置数据源
        wheelHour2.setSeletion(0);// 默认选中第三项
        wheelHour2.setOnWheelViewListener(object : WheelView.OnWheelViewListener() {
            override fun onSelected(selectedIndex: Int, item: String?) {
                super.onSelected(selectedIndex, item)
                houtStr2 = item.checkValue()
            }
        })
        wheelMinute2.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelMinute2.setItems(minuteList);// 设置数据源
        wheelMinute2.setSeletion(0);// 默认选中第三项
        wheelMinute2.setOnWheelViewListener(object : WheelView.OnWheelViewListener() {
            override fun onSelected(selectedIndex: Int, item: String?) {
                super.onSelected(selectedIndex, item)
                minuteStr2 = item.checkValue()
            }
        })
        window.findViewById<TextView>(R.id.tv_ok).setOnClickListener {
            callback.onOkClick("${houtStr1}:${minuteStr1}", "${houtStr2}:${minuteStr2}")
            dialog.dismiss()
        }
    }

}